package com.roadjava.util;

import com.alibaba.fastjson.JSON;
import com.roadjava.res.ResultDTO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

/**
 * @author zhaodaowen
 * @see <a href="http://www.roadjava.com">乐之者java</a>
 */
public class ResponseUtil {

    public static void respTxtHtml(HttpServletResponse resp, String result) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        write(resp, result);
    }

    private static void write(HttpServletResponse resp, String result) {
        PrintWriter writer=null;
        try {
            writer = resp.getWriter();
            writer.print(result);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if (writer!=null) {
                writer.close();
            }
        }
    }

    public static void respTxtPlain(HttpServletResponse resp, String result) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/plain;charset=utf-8");
        write(resp,result);
    }

    public static void respAppJson(HttpServletResponse resp, ResultDTO dto) {
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json;charset=utf-8");
        write(resp, JSON.toJSONString(dto));
    }

}
